package initialize

import (
	"common/global"
	"context"
	"fmt"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func InitMonGoDb() {
	cf := Config.Mongodb
	clientOptions := options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%d", cf.Hort, cf.Port)).SetMaxPoolSize(1000)
	clientOptions.SetAuth(options.Credential{
		Username: cf.User,
		Password: cf.Passwd,
	})
	ctx, cancel := context.WithTimeout(global.EmptyCtx, 10*time.Second)
	defer cancel()
	var err error
	global.MonGoDbClient, err = mongo.Connect(ctx, clientOptions)
	if err != nil {
		panic(err)
	}
	err = global.MonGoDbClient.Ping(ctx, nil)
	if err != nil {
		panic(err)
	}
	global.MonGoDatabase = global.MonGoDbClient.Database(cf.Database)
	fmt.Println("init MonGODb success")

	// 添加唯一索引，防止重复插入
	coll := global.MonGoDatabase.Collection("pending_binding_requests")
	indexModel := mongo.IndexModel{
		Keys:    map[string]interface{}{"user_id": 1, "device_id": 1, "request_type": 1},
		Options: options.Index().SetUnique(true),
	}
	_, _ = coll.Indexes().CreateOne(context.Background(), indexModel)
}
